package runtime

import (
	"fmt"
	"gitee.com/xcy871622040/gameframe/cluster/settings"
	"github.com/smallnest/rpcx/client"
	"log"
)

type DefaultRuntime struct {
	ShareingPlugin

	serial      uint16
	extAddress  string
	serviceName string
}

func NewDefaultRuntime() Runtime {
	return new(DefaultRuntime)
}

// Init 初始化
func (dr *DefaultRuntime) Init(serviceaddress string, setting *settings.Setting, serial uint16) {
	dr.serial = serial
	dr.extAddress = serviceaddress
	dr.serviceName = setting.ServiceName

	var ServiceTypes []string
	for svc := range setting.ServicePort {
		ServiceTypes = append(ServiceTypes, svc)
	}

	// 创建服务注册和服务发现组件
	switch setting.Registration {
	case "etcd":
		dr.EtcdDiscovery(setting.ETCDUrl, setting.BasePath)
		dr.EtcdRegisterPlugin(serviceaddress, setting.ETCDUrl, setting.BasePath)
	case "redis":
		dr.EtcdDiscovery(setting.RedisUrl, setting.BasePath)
		dr.EtcdRegisterPlugin(serviceaddress, setting.RedisUrl, setting.BasePath)
	case "peer2peer":
		pairs := map[string][]*client.KVPair{}
		for svc, addrs := range setting.RpcxService {
			for _, addr := range addrs {
				pairs[svc] = append(pairs[svc], &client.KVPair{Key: addr[0], Value: addr[1]})
			}
		}
		dr.Peer2PeerRegisterPlugin(setting.BasePath)
		dr.MultipleServersDiscovery(pairs, setting.BasePath)
	default:
		log.Fatal("No service governance component is configured")
	}
}

// Ready 设置节点可以对外提供服务
func (dr *DefaultRuntime) Ready() {}

// Allocate 设置节点被分配（处理服务中）
func (dr *DefaultRuntime) Allocate() {}

// Shutdown 设置节点准备关闭（空闲中的节点会直接关闭）
func (dr *DefaultRuntime) Shutdown() {}

// ServiceName 节点服务类型
func (dr *DefaultRuntime) ServiceName() string {
	return dr.serviceName
}

// ExternalAddress 节点对外地址
func (dr *DefaultRuntime) ExternalAddress() string {
	return dr.extAddress
}

// GenerateServerId 获取当前服务的id (名字-序号)
func (dr *DefaultRuntime) GenerateServerId() string {
	return fmt.Sprintf("%s-%d", dr.serviceName, dr.serial)
}
